package com.oude.httpclient.ui.fragment;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.oude.httpclient.R;
import com.squareup.okhttp.CacheControl;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;

public class FirstFragment extends Fragment {
    //返回码
    public static final int Success = 200;
    public static final int Fail = 500;
    //下拉表
    private ArrayAdapter<String> adapter_first1, adapter_first2;
    private String server_ip, server_port,access_path01,access_path02;
    private Spinner sp_first1, sp_first2;
    //网页
    private WebView webView;

    public FirstFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    //初始化布局
    private void initView() {
        //控件绑定
        sp_first1 = getActivity().findViewById(R.id.first_Spinner1);
        sp_first2 = getActivity().findViewById(R.id.first_Spinner2);
        Button bn_visit = getActivity().findViewById(R.id.first_visit);
        webView = getActivity().findViewById(R.id.webView01);
        //下拉表
        //父下拉表，下拉内容固定
        String[] array_first1 = this.getResources().getStringArray(R.array.first_spinner1_item);
        adapter_first1 = new ArrayAdapter<String>(getActivity(), R.layout.spinner_item, array_first1);
        adapter_first1.setDropDownViewResource(R.layout.spinner_down);
        sp_first1.setAdapter(adapter_first1);
        sp_first1.setOnItemSelectedListener(new spinnerListener());
        //绑定控件
        bn_visit.setOnClickListener(new VistiClickListener());

    }

    //下拉表关联实现
    class spinnerListener implements AdapterView.OnItemSelectedListener {

        @Override
        public void onItemSelected(AdapterView<?> p1, View p2, int p3, long p4) {
            switch (p3) {
                case 0:
                    String[] array_first2 = getActivity().getResources().getStringArray(R.array.first_spinner2_item);
                    adapter_first2 = new ArrayAdapter<String>(getActivity(), R.layout.spinner_item, array_first2);
                    adapter_first2.setDropDownViewResource(R.layout.spinner_down);
                    sp_first2.setAdapter(adapter_first2);
                    break;
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> p1) {
            // TODO: Implement this method
        }

    }

    //--------各框架访问方法--------
    class VistiClickListener implements View.OnClickListener {
        @Override
        public void onClick(View p1) {
            webView.loadData("loading...", "text/html", "UTF-8");
            //获取设置信息
            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
            server_ip = sp.getString("server_ip", "127.0.0.1");
            server_port = sp.getString("server_port", "80");
            access_path01 = sp.getString("access_path01", "");
            access_path02 = sp.getString("access_path02", "");
            //获取下拉表内容
            String[] sp1_array = getResources().getStringArray(R.array.first_spinner1_item);
            String[] sp2_array = getResources().getStringArray(R.array.first_spinner2_item);
            String sp1_value = sp_first1.getSelectedItem().toString();
            String sp2_value = sp_first2.getSelectedItem().toString();
            //HTTPClient访问
            if (sp1_value.equals(sp1_array[0])) {
                if (sp2_value.equals(sp2_array[0])) {
                    HttpClientTest(0);
                }
                if (sp2_value.equals(sp2_array[1])) {
                    HttpClientTest(1);
                }
            }
            //HttpURLConnection访问
            if (sp1_value.equals(sp1_array[1])) {
                if (sp2_value.equals(sp2_array[0])) {
                    HttpURLConnectionTest(0);
                }
                if (sp2_value.equals(sp2_array[1])) {
                    HttpURLConnectionTest(1);
                }
            }

            //OkHttp2访问
            if (sp1_value.equals(sp1_array[2])) {
                if (sp2_value.equals(sp2_array[0])) {
                    OkHttp2Test(0);
                }
                if (sp2_value.equals(sp2_array[1])) {
                    OkHttp2Test(1);
                }
            }

            //Volley访问
            if (sp1_value.equals(sp1_array[3])) {
                if (sp2_value.equals(sp2_array[0])) {
                    VolleyTest(0);
                }
                if (sp2_value.equals(sp2_array[1])) {
                    VolleyTest(1);
                }
            }

        }
    }


    //根据返回码判断反馈是否发送成功
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Success:
                    Log.i("FirstFragment-HTTPClientTest-Handle", "返回内容：" + msg.obj);
                    webView.loadData(String.valueOf(msg.obj), "text/html", "UTF-8");
                    break;
                case Fail:
                    webView.loadData("访问失败！", "text/html", "UTF-8");
                    break;
                default:
                    break;
            }
        }
    };

    //HTTPClient
    private void HttpClientTest(final Integer flag) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = "";
                String targetUrl = "";
                switch (flag) {
                    case 0:
                        targetUrl = "http://" + server_ip + ":" + server_port + access_path01;
                        break;
                    case 1:
                        targetUrl = "http://" + server_ip + ":" + server_port + access_path02;
                        break;
                }

                Log.i("FirstFragment-HTTPClientTest-URL", "访问地址：" + targetUrl);

                HttpClient httpclient = new DefaultHttpClient();
                httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
                httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
                HttpGet httpget = new HttpGet(targetUrl);
                try {
                    HttpResponse response = httpclient.execute(httpget);
                    HttpEntity entity = response.getEntity();
                    Log.i("FirstFragment-HTTPClientTest-status", "返回码：" + response.getStatusLine().getStatusCode());
                    InputStream is = entity.getContent();
                    BufferedReader in = new BufferedReader(new InputStreamReader(is));
                    StringBuffer buffer = new StringBuffer();
                    String line = "";
                    while ((line = in.readLine()) != null) {
                        buffer.append(line);
                    }
                    result = buffer.toString();
                    if (result != "") {
                        Message httpClienMessage = new Message();
                        httpClienMessage.obj = result;
                        handler.obtainMessage(Success, result).sendToTarget();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    Message httpClienMessage = new Message();
                    httpClienMessage.what = Fail;
                    handler.sendMessage(httpClienMessage);
                } finally {
                    httpclient.getConnectionManager().shutdown();
                }

            }
        }).start();
    }

    //HttpURLConnection
    private void HttpURLConnectionTest(final Integer flag) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                String result = "";
                String targetUrl = "";
                Integer statusCode = 0;
                switch (flag) {
                    case 0:
                        targetUrl = "http://" + server_ip + ":" + server_port + access_path01;
                        break;
                    case 1:
                        targetUrl = "http://" + server_ip + ":" + server_port + access_path02;
                        break;
                }
                Log.i("FirstFragment-HttpURLConnection-targetUrl", "targetUrl：" + targetUrl);
                try {
                    //使用url加载路径
                    URL url = new URL(targetUrl);
                    //创建HttpURLConnection对象
                    connection = (HttpURLConnection) url.openConnection();
                    //设置超时
                    connection.setConnectTimeout(5000);
                    connection.setReadTimeout(5000);
                    connection.setRequestMethod("GET");
                    statusCode = connection.getResponseCode();
                    Log.i("FirstFragment-HttpURLConnection-statusCode", "statusCode：" + statusCode);
                    if (statusCode == 200) {
                        InputStream inputStream = connection.getInputStream();
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        int len = 0;
                        while ((len = inputStream.read(buffer)) != -1) {
                            bos.write(buffer, 0, len);
                        }
                        inputStream.close();
                        bos.close();
                        result = bos.toString();
                    }
                    if (result != "") {
                        Message httpURLConnectionMessage = new Message();
                        httpURLConnectionMessage.obj = result;
                        handler.obtainMessage(Success, result).sendToTarget();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    Message message = new Message();
                    message.what = Fail;
                    handler.sendMessage(message);
                } finally {
                    //关闭连接
                    connection.disconnect();
                }
            }
        }).start();

    }

    //OkHttp2
    private void OkHttp2Test(final Integer flag) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = "";
                String targetUrl = "";
                switch (flag) {
                    case 0:
                        targetUrl = "http://" + server_ip + ":" + server_port + access_path01;
                        break;
                    case 1:
                        targetUrl = "http://" + server_ip + ":" + server_port + access_path02;
                        break;
                }
                Log.i("FirstFragment-OkHttp2-targetUrl", "targetUrl：" + targetUrl);
                OkHttpClient mOkHttpClient = new OkHttpClient();
                //创建请求Request
                mOkHttpClient.setConnectTimeout(5, TimeUnit.SECONDS);
                final Request request = new Request.Builder().url(targetUrl).cacheControl(CacheControl.FORCE_NETWORK).build();
                Call call = mOkHttpClient.newCall(request);
                try {
                    Response mResponse = call.execute();
                    if (mResponse.isSuccessful()) {
                        result = mResponse.body().string();
                        Log.i("FirstFragment-OkHttp2-result", "内容：" + result);
                        if (result != "") {
                            Message OkHttp2Message = new Message();
                            OkHttp2Message.obj = result;
                            handler.obtainMessage(Success, result).sendToTarget();
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    Message message = new Message();
                    message.what = Fail;
                    handler.sendMessage(message);
                }

            }
        }).start();
    }

    //Volley
    private void VolleyTest(final Integer flag) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String targetUrl = "";
                switch (flag) {
                    case 0:
                        targetUrl = "http://" + server_ip + ":" + server_port + access_path01;
                        break;
                    case 1:
                        targetUrl = "http://" + server_ip + ":" + server_port + access_path02;
                        break;
                }
                Log.i("FirstFragment-Volley-targetUrl", "targetUrl：" + targetUrl);

                StringRequest mStringRequest = new StringRequest(targetUrl, new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        String result = response.toString();
                        Log.i("FirstFragment-Volley-result", "内容：" + result);
                        if (result != "") {
                            Message VolleyMessage = new Message();
                            VolleyMessage.obj = result;
                            handler.obtainMessage(Success, result).sendToTarget();
                        }

                    }

                }, new com.android.volley.Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Message message = new Message();
                        message.what = Fail;
                        handler.sendMessage(message);
                    }
                });

                RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
                requestQueue.add(mStringRequest);
                requestQueue.start();
            }
        }).start();
    }

}
